﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class LocalVariableRule : ILRule<LocalVariableHandle>
    {
        [ILInfo(true)]
        public int Index { get; }

        [ILInfo(true)]
        public string Name { get; }

        [ILInfo]
        public LocalVariableAttributes Attributes { get; }

        public LocalVariableRule(
            LocalVariableAttributes attributes,
            int index,
            string name)
            : base()
        {
            Attributes = attributes;
            Index = index;
            Name = name;
        }

        public LocalVariableRule(MetadataReader reader, LocalVariableHandle localVariableHandle)
            : base(reader)
        {
            LocalVariable localVariable = reader.GetLocalVariable(localVariableHandle);
            Attributes = localVariable.Attributes;
            Index = localVariable.Index;
            Name = reader.GetString(localVariable.Name);
        }

        public override LocalVariableHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            LocalVariableHandle localVariableHandle = builder.AddLocalVariable(
                attributes: Attributes,
                index: Index,
                name: Name == null ? default : builder.GetOrAddString(Name));
            designer.LocalVariableNumber.Increment();
            return localVariableHandle;
        }
    }
}